# celery的任务必须写在tasks.py的文件中，别的文件名称不识别!!!
import asyncio
from mycelery.main import app
from mycelery.order import async_order
from mycelery.main import mysql_pool
from mycelery.redis_pool import RedisPool
import redis
import pymysql
import time


@app.task  # name表示设置任务的名称，如果不填写，则默认使用函数名做为任务名
def send_sms():
    """发送短信"""
    orders = mysql_pool.fetch_all('select order_id from `order` where status = %s', (0, ))
    if not orders:
        return '没有啦'
    order_ids = []
    for order in orders:
        order_ids.append(order.get('order_id'))
    # 去redis连接池获取一个连接
    redis_conn = redis.Redis(connection_pool=RedisPool)
    # pl = redis_conn.pipeline()
    order_ids_canceled = {}
    for order_id in order_ids:
        res = redis_conn.ttl(order_id)
        order_ids_canceled[order_id] = res
    # pl.execute()
    redis_conn.close()
    print('*****', order_ids_canceled)
    for order_id, val in order_ids_canceled.items():
        if order_ids_canceled[order_id] not in (-1, -2):
            order_ids_canceled.pop(order_id)
    tasks = []
    print('yyy', order_ids_canceled)
    for order_id in order_ids_canceled.keys():
        tasks.append(asyncio.ensure_future(async_order.update_order_status(order_id)))
    if not tasks:
        return '订单都还没过期呢'
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    # loop.close()
    return "send_sms OK"

@app.task  # name表示设置任务的名称，如果不填写，则默认使用函数名做为任务名
def send_sms2(mobile):
    print("向手机号%s发送短信成功!" % mobile)
    time.sleep(5)

    return "send_sms2 OK"
